<template>
  <div
    class="media-center"
    :class="{'fetching-box': listFetching}">
    <el-container>
        <el-main class="leftMain">
          <div class="mediaTree">
            <el-tabs style="height: 100%" v-model="activeName" type="border-card">
              <el-tab-pane :label="$t('目录管理')" name="first">
                <media-menu-tree
                  style="min-height: 550px"
                  :is-can-check="false"
                  @currentNodeData="currentNodeDataChange"
                  :expand-on-click-node="false"
                  :isNoAction="true"
                  :api-obj="menuApiObj"
                  :api-type="'5'" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-main>
        <el-main class="rightMain">
          <el-tabs class="rightMain-tabs" style="height: 44px" v-model="activeName2" @tab-click="auditTabClick">
            <el-tab-pane :label="$t('待审核')" name="first"></el-tab-pane>
            <el-tab-pane :label="$t('已通过')" name="second"></el-tab-pane>
            <el-tab-pane :label="$t('未通过')" name="third"></el-tab-pane>
          </el-tabs>
          <bs-main height="calc(100% - 44px)">
            <condition-row
              slot="header"
              :activeName="activeName2"
              @action="(data) => handCondition('action', data)"
              @del="handCondition('del')"
              @refresh="handCondition('refresh')"
              @agree="handCondition('agree')"
              @unAgree="handCondition('unAgree')"
              @search="(data) => handCondition('search', data)"
              @insert="handCondition('insert')"
              ></condition-row>
            <pagination
              slot="footer"
              :total="page.total"
              :page="page.current"
              :limit="page.size"
              :page-sizes="page.sizes"
              @pagination="pageChange"></pagination>
            
            <div style="height: 100%;" v-loading="listFetching">
              <div style="margin-left: -15px;">
                <mini-panel
                  ref="miniPanel"
                  class="center"
                  :tempType="tempType"   
                  :datas="mediaData"
                  @dbClick="_openPreView" />
              </div>
            </div>
          </bs-main>
        </el-main>
    </el-container>
    <preview-dialog :visible.sync="previewDialog.show" :pre-data="previewDialog.preData" />
    <examine-dialog :is-show-type="true" :type="showType" :visible.sync="showExamineDialog" @examine="handleExamine" />
    <insert-notice-dialog :visible.sync="showInsertNoticeDialog"></insert-notice-dialog>
  </div>
</template>

<script>
import MediaMenuTree from '../components/MediaMenuTree'
import MiniPanel from '../components/MiniPanel'
import Pagination from '@/components/Pagination'
import ConditionRow from './components/ConditionRow'
import PreviewDialog from '../components/PreviewDialog'
import ExamineDialog from '../components/ExamineDialog'
import InsertNoticeDialog from './components/InsertNoticeDialog'
import {genMediaMixin, MEDIA_MIXIN_CONST} from '@/mixins/mediaMixins.js'
import {fileTypeMap, webImageUrl, fileTypeOpts, FILETYPE} from '../media-center/const'
import MediaApi from '@/api/media'
import CommonApi from '@/api/common'
import { createNamespacedHelpers } from 'vuex'
const {mapGetters, mapActions} = createNamespacedHelpers('media')
import {getFileSize} from '@/utils'
import { requestOpts } from '@/utils/request.js'
// import fileDownload from 'js-file-download';
// import Axios from 'axios'

export default {
  mixins: [genMediaMixin(MEDIA_MIXIN_CONST.TYPE_MEDIA_AUDIT)],
  filters: {
    getFileSize
  },
  components: {
    PreviewDialog,
    MediaMenuTree,
    MiniPanel,
    Pagination,
    ConditionRow,
    ExamineDialog,
    InsertNoticeDialog
  },
  data() {
    return {
      menuApiObj: {
        get: MediaApi.getCatalogue,
        add: MediaApi.saveCatalogue,
        update: MediaApi.updateCatalogue,
        del: MediaApi.delCatalogue,
        bottomGet: MediaApi.getFollow,
        getOtherMedia: MediaApi.getOtherMedia
      },
      previewDialog: {
        show: false
      },
      activeName: 'first',
      activeName2: 'first',
      search: {
        queryType: 0,
        queryParam: ''
      },
      sort: {
        orders: '',
        sortField: ''
      },
      tagIds: '',
      showExamineDialog: false,
      showInsertNoticeDialog: false,
      showType: 'media',
      tempType: 'audit'
    }
  },
  computed:{
    ...mapGetters(['tagList']),
    searchUserId() {
      return this.search.ownerUserId ? this.search.ownerUserId : ''
    },
    uploadDialogShow: {
      get() {
        return this.$store.state.media.isQuikUpload
      },
      set(val) {
        this.$store.dispatch('media/changeQuikUpload', {
          key: 'isQuikUpload',
          value: false
        })
      }
    }
  },
  watch: {
    activeName(v) {
      console.log(v)
      if (v === 'second') {
        this.getTagList()
      } else {
        this.tagIds = ''
      }
    }
  },
  created () {
    this.pageChange({page: this.page.current, limit: this.page.size})
    this.getTagList()
  },
  methods: {
    ...mapActions(['getTagList', 'getTagTree']),
    handleTagClick(t) {
      this.tagIds = t.id
      this.page.current = 1
      this.fetchList()
      console.log('tag按下', t)
    },
    // handleEditClick(row) {
    //   if (this._isSubOrOther()) return
    //   console.log('edit', row)
    //   this._openEditView(row)
    // },
    handleDelClick(row) {
      if (this._isSubOrOther()) return
      this._handleDel(row)
      console.log('del', row)
    },
    handleListSort({type, prop}) {
      if (this.sortFieldMap[prop]) {
        this.sort = {
          sortField: this.sortFieldMap[prop],
          orders: type.toLowerCase()
        }
        this.fetchList()
      }
    },
    auditTabClick() {
      this.page.current = 1
      this.fetchList()
    },
    getActiveItem() {
      return this.$refs.miniPanel.getActiveItem()
    },
    _isSubOrOther() {
      if (this.folderId === -1 || this.folderId === -2 || this.isOtherMenu) {
        this.$alert('提示', '此目录不可操作')
        return true
      }
      return false
    },
    handCondition(type, data) {
      switch(type) {
        case 'action':
          this._handleAction(data)
          break;
        case 'del':
          if (this._isSubOrOther()) return
          this._handleDel(
            this.getActiveItem()
          )
          break;
        case 'refresh':
          this._handleRefresh()
          break;
        case 'search':
          this._handleSearch(data)
          break;
        case 'agree':
          this._handleAgree('agree', this.getActiveItem())
          break
        case 'unAgree':
          this._handleAgree('unAgree', this.getActiveItem())
          break
        case 'insert':
          this._handleInsertNotice()
          break
        default: console.log('未知操作');
      }
    },
    _handleAgree(type, data) {
      if(type === 'agree') {
        if(!data) {
          this.$message.error('请选择要审核的记录')
          return
        }
        this.$confirm('提示', '是否确认通过审核？').then(bool => {
          bool && this.mediaAudit(1, '', data)
        })
      } else if(type === 'unAgree') {
        this.showExamineDialog = true
      }
    },
    async handleExamine(v, msg, cb) {
      const data = this.getActiveItem()
      this.mediaAudit(-1, msg, data)
      this.showExamineDialog = false
    },
    // 紧急插播
    _handleInsertNotice() {
      this.showInsertNoticeDialog = true
    },
    _handleAction(type) {
      switch(type) {
        case '上传':
          if (this._isSubOrOther()) return
          this.$store.dispatch('media/changeQuikUpload', {
            key: 'isQuikUpload',
            value: true
          })
          break;
        case '下载':
          this._openDownLoad(
            this.getActiveItem()
          )
          break;
        case '预览':
          this._openPreView(
            this.getActiveItem()
          )
          break;
        default:
      }
    },
    _handleSearch({name, value}) {
      this.search = {
        ...this.search,
        queryParam: value,
        queryType: name
      }
      this.page.current = 1
      this.fetchList()
    },
    _handleRefresh() {
      this.fetchList()
      this.$message.success('刷新成功')
    },
    async _openDownLoad(file) {
      if (!file) {
        this.$alert('提示', '请先选择文件')
        return
      }
      if (file instanceof Array) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      const passFileType = [ // 能下载的文件
        FILETYPE.TEXT,
        FILETYPE.VIDEO,
        FILETYPE.AUDIO,
        FILETYPE.LOCAL_TEXT,
        FILETYPE.QRCODE,
        FILETYPE.PICTURE,
        FILETYPE.NET_PICTURE,
        FILETYPE.WEB_CAPTURE
      ]
      if (passFileType.indexOf(String(file.type)) === -1) return this.$alert('提示', '对不起，该媒体类型无法下载')
      if (file.path) {
        const previewTokenRes = file.path ? await CommonApi.previewToken({path: encodeURIComponent(file.path)}) : null
        var tempwindow=window.open('_blank');
        tempwindow.location.href = previewTokenRes ? previewTokenRes : file.path
      } else {
        this.$message.error('对不起，未获取到文件地址，无法下载')
      }
    },
    async _openPreView(file) {
      if (!file) {
        this.$alert('提示', '请先选择文件')
        return
      }
      if (file instanceof Array) {
        this.$alert('提示', '此操作不支持多选')
        return
      }
      const passFileType = [ // 能预览的文件类型
        FILETYPE.VIDEO,
        FILETYPE.AUDIO,
        FILETYPE.TEXT,
        FILETYPE.LOCAL_TEXT,
        FILETYPE.QRCODE,
        FILETYPE.NET_PICTURE,
        FILETYPE.PICTURE,
        FILETYPE.WEB_CAPTURE
      ]
      // if (passFileType.indexOf(String(file.type)) === -1) return this.$alert('提示', '对不起，该媒体类型无法预览')
      // 重新获取url的token
      const previewTokenRes = file.path ? await CommonApi.previewToken({path: encodeURIComponent(file.path)}) : null
      const _isText = [FILETYPE.TEXT,FILETYPE.LOCAL_TEXT].some(i => i === String(file.type))
      const _isNET_PICTURE = String(file.type) === FILETYPE.NET_PICTURE
      if (_isText || _isNET_PICTURE) {
        // 获取文本文件内容
        const preContent = await MediaApi.getLocalInfo({path: previewTokenRes ? previewTokenRes : file.path})
        const res = await MediaApi.getInfo({id: file.id}) 
        if(res) {
          let argus = res.argus ? JSON.parse(res.argus) : {}
          let attributes = argus.attributes
          if (attributes && typeof attributes === 'string') {
            attributes = JSON.parse(attributes)
          }
          this.previewDialog = {
            ...this.previewDialog,
            show: true,
            preData: {
              ...argus,
              ...file,
              ...res,
              ...attributes,
              showType: 3,
              _isText
            }
          }
          if(preContent) {
            this.previewDialog.preData.content = preContent
          }
        }
      } else {
        this.previewDialog = {
          ...this.previewDialog,
          show: true,
          preData: {
            ...file,
            showType: 3,
            _isText: false
          }
        }
        if(previewTokenRes) {
          this.previewDialog.preData.path = previewTokenRes
        }
      }
    },
    _handleDel(file) {
      if (!file) {
        this.$alert('提示', '请先选择文件')
        return
      }
      let bool = false
      if (file instanceof Array) {
        file.forEach(item => {
          if(item.refCount > 0) {
            bool = true
            return
          }
        })
      }else{
        if(file.refCount > 0) {
          bool = true
        }
      }
      if(bool) {
        this.$alert('提示', '选择的媒体已被使用,不能删除')
        return
      }
      this.$confirm('提示', '是否确认删除？').then(bool => {
        bool && this.delMedia(file)
      })
    },

    te(arg) {
        const hasKey = this.$te(arg)
        if (hasKey) {
        const result = this.$t(arg)
        return result
        }
        return arg
    },

  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';
.mediaTree {
  width: 100%;
  .el-tabs--border-card {
    border: 0 !important;
  }
  ::v-deep .el-tabs--border-card .el-tabs__content {
    padding: 0;
  }
}
.mediaTree {
  // overflow-x: scroll;
  ::v-deep .el-tabs__item {
    padding: 0 !important;
    width: 125px;
    text-align: center;
  }
  ::v-deep .el-tabs__item:last-child {
    border-right: 0 !important;
  }
  // ::v-deep .el-tabs__item.is-active{background: #fff;border-bottom:0 !important;
  //   }
}
// .leftMain >>> .el-tabs__content {
//   padding-left: 0;
//   padding-right: 0;
// }
// .leftMain {
//   ::v-deep .el-tabs__item{padding:0 !important; width:125px; text-align:center;height: 44px !important; line-height: 44px !important;}
//   ::v-deep .el-tabs__item:last-child{border-right:0 !important;}
// }
</style>

<style>
.media-center .rightMain .el-tabs {
  border-bottom: 0;
}
.media-center .rightMain .el-tabs__content {
  padding: 0;
}
.el-tabs--border-card{border: 0 !important;}
.el-button-group .el-button--primary:last-child {
  height: 32px;
}
.el-button-group .el-button--primary:first-child {
    height: 30px;
}
</style>